/**
 * 
 */
package fr.fermeManager.library.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import fr.fermeManager.library.model.beans.Transaction;
import fr.fermeManager.library.utils.MybatisUtil;

/**
 * @author Mo
 * 
 */
public class DaoTransactionImplDerby implements DaoTransaction {
	
	
	private SqlSession session = MybatisUtil.getSession();

	@Override
	public List<Transaction> getFermeTransactions(int idferme,boolean isAdmin) throws Exception {
		
		List<Transaction> listeTransactions = new ArrayList<Transaction>();

		try {
			
			Map<String,Object> parameters = new HashMap<String, Object>();
			
			parameters.put("idferme", idferme);
			parameters.put("isAdmin", isAdmin);
			
			listeTransactions = session.selectList("selectTransactions",parameters);
			
		} catch (Exception e) {
			session.rollback();
			throw e;
		}

		return listeTransactions;
	}

	@Override
	public Transaction ajouterTransaction(int idFerme, Transaction nouveauTransac) throws Exception {
		
		try {
			
			Map<String,Object> parameters = new HashMap<String, Object>();
			
			parameters.put("idFerme", idFerme);
			parameters.put("nouveauTransac", nouveauTransac);
			
			session.insert("ajouterTransaction",parameters);
			
			session.commit();
			
			return nouveauTransac;
			
		} catch (Exception e) {
			session.rollback();
			throw e;
		}
	}

	@Override
	public void supprimerTransaction(int idTransaction) throws Exception {
		
		try {
			
			session.delete("effacerTransaction",idTransaction);
			
			session.commit();
			
		} catch (Exception e) {
			session.rollback();
			throw e;
		}
		
	}

	@Override
	public void modifierTransaction(Transaction transacParam) throws Exception {
		
		try {
			
			session.update("modifierTransaction",transacParam);
			
			session.commit();
			
		} catch (Exception e) {
			session.rollback();
			throw e;
		}
		
	}

	@Override
	public boolean existeTransactionsActifsForFerme(int idFerme) throws Exception {
		
		int nbActifs =0;
		
		try {
			
			nbActifs = session.selectOne("existeTransactionsActifsForFerme",idFerme);
			
		} catch (Exception e) {
			session.rollback();
			throw e;
		}
		return (nbActifs>0);
	}
	
	@Override
	public boolean existeTransactionsActifsForTypeTransaction(int idTypeTransaction) throws Exception {
		int nbActifs =0;
		
		try {
			
			nbActifs = session.selectOne("existeTransactionsActifsForTypeTransaction",idTypeTransaction);
			
		} catch (Exception e) {
			session.rollback();
			throw e;
		}
		return (nbActifs>0);
	}
}
